package z.explorer.ui.common;

import javax.swing.*;

import java.awt.BorderLayout;
import java.util.*;
import java.util.List;
import java.util.regex.PatternSyntaxException;

import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableRowSorter;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import z.explorer.Main;

import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

public class ZTablePanel extends JPanel {

	private static final long serialVersionUID = 2507012600029917393L;
	private static Log log = LogFactory.getLog(ZTablePanel.class);

	ZTable zTable = null;

	JTextField searchField = new JTextField();

	JLabel searchLabel = new JLabel("filter");

	public ZTablePanel(List list) {

		zTable = new ZTable(list);
		initUI();
	}
	
	public ZTablePanel(List list,boolean editable){
		zTable = new ZTable(list,editable);
		initUI();
	}

	public boolean isEditable(){
		return zTable.isEditable();
	}
	
	public ZTable getZTable(){
		return zTable;
	}
	
	public void reloadData(List list) {
		if(zTable == null)
			zTable = new ZTable(list);
		zTable.reloadData(list);
		zTable.clearSelection();
	}

	private void initUI() {
		zTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		JPanel jp = new JPanel();
		jp.setLayout(new BorderLayout());
		jp.add(searchLabel, BorderLayout.WEST);
		jp.add(searchField, BorderLayout.CENTER);
		JScrollPane sp = new JScrollPane(zTable,
				JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
				JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);

		setLayout(new BorderLayout());
		add(jp, BorderLayout.NORTH);
		add(sp, BorderLayout.CENTER);

		searchField.addKeyListener(new KeyAdapter() {
			
			public void keyReleased(KeyEvent e) {
				String text = searchField.getText();
				TableRowSorter<ZTableModel> sorter = zTable.getSorter();
				if (text.length() == 0) {
					sorter.setRowFilter(null);
				} else {
					try {
						sorter.setRowFilter(RowFilter.regexFilter(text,
								new int[] {}));
					} catch (PatternSyntaxException pse) {
						log.error("Bad regex pattern");
					}
				}
			}
		});

	}
}
